import React, { useState, useEffect } from 'react';
import { Card } from '../../components/Card';
import { Button } from '../../components/Button';
import { useChromeStorage } from '../../hooks/useChromeStorage';
import './NewsTab.css';

export const NewsTab = () => {
  const [rssArticles, setRssArticles] = useState([]);
  const [favorites, setFavorites] = useState([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    chrome.storage.local.get(['rssArticles', 'favorites'], (result) => {
      setRssArticles(result.rssArticles || []);
      setFavorites(result.favorites || []);
      setLoading(false);
    });
  };

  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      chrome.runtime.sendMessage({ action: 'fetchRSS' }, (response) => {
        if (chrome.runtime.lastError) {
          console.error('Error refreshing RSS:', chrome.runtime.lastError);
        } else {
          loadData();
        }
        setRefreshing(false);
      });
    } catch (error) {
      console.error('Error refreshing RSS:', error);
      setRefreshing(false);
    }
  };

  const handleFavorite = async (id) => {
    const newFavorites = favorites.includes(id)
      ? favorites.filter(f => f !== id)
      : [...favorites, id];
    
    await chrome.storage.local.set({ favorites: newFavorites });
    setFavorites(newFavorites);
  };

  const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
      const date = new Date(dateString);
      const now = new Date();
      const diffMs = now - date;
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) return 'Today';
      if (diffDays === 1) return 'Yesterday';
      if (diffDays < 7) return `${diffDays} days ago`;
      return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    } catch (e) {
      return '';
    }
  };

  if (loading) {
    return <div className="loading">Loading news...</div>;
  }

  const sortedArticles = [...rssArticles].sort((a, b) => {
    const dateA = a.pubDate ? new Date(a.pubDate).getTime() : a.timestamp || 0;
    const dateB = b.pubDate ? new Date(b.pubDate).getTime() : b.timestamp || 0;
    return dateB - dateA;
  });

  return (
    <div className="news-tab">
      <div className="section-header">
        <h2>Longevity News</h2>
        <Button onClick={handleRefresh} disabled={refreshing}>
          {refreshing ? '⏳' : '🔄'}
        </Button>
      </div>

      {sortedArticles.length === 0 ? (
        <div className="empty-state">
          <p>No news articles available.</p>
          <p style={{ fontSize: '12px', marginTop: '8px', color: 'rgba(255, 255, 255, 0.5)' }}>
            Click the refresh button to load articles from Lifespan.io
          </p>
        </div>
      ) : (
        <div className="news-list">
          {sortedArticles.map((article) => {
            const isFavorite = favorites.includes(article.id);
            const link = article.link || '#';
            const categories = article.categories || [];
            const categoryText = categories.length > 0 ? categories[0] : 'News';
            
            return (
              <Card
                key={article.id}
                className="news-card"
                onClick={() => link !== '#' && chrome.tabs.create({ url: link })}
              >
                {article.imageUrl && (
                  <div className="news-image">
                    <img src={article.imageUrl} alt={article.title} onError={(e) => e.target.style.display = 'none'} />
                  </div>
                )}
                <div className="news-content">
                  <div className="news-header">
                    <span className="news-category">{categoryText}</span>
                    {article.pubDate && <span className="news-date">{formatDate(article.pubDate)}</span>}
                  </div>
                  <h3>
                    {article.title}
                    <button
                      className={`favorite-btn ${isFavorite ? 'active' : ''}`}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleFavorite(article.id);
                      }}
                    >
                      {isFavorite ? '⭐' : '☆'}
                    </button>
                  </h3>
                  {article.description && (
                    <p className="news-description">{article.description}</p>
                  )}
                  <div className="news-footer">
                    <span className="news-source">{article.source || 'Lifespan.io'}</span>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
};

